package com.study.callablefuture;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 线程之callable/future应用
 */
public class Demo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long currentTime1 = System.currentTimeMillis();
        for (long i = 0; i <10000000000L ; i++) {
        }
        for (long i = 0; i <10000000000L ; i++) {
        }
        System.out.println("正常执行用时："+(System.currentTimeMillis()-currentTime1)/1000.00+"s");
        //使用callable/futrue
        long currentTime2 = System.currentTimeMillis();
//        byte bytes[] = new byte[1024];
//        List list = new ArrayList<>();
        FutureTask<Integer> futureTask1 = new FutureTask<Integer>(new Callable() {
            @Override
            public Integer call() throws Exception {
                System.out.println("开始执行futureTask1");
                for (long i = 0; i <1000000000L ; i++) {
                }
                return 1;
            }
        });
        FutureTask<Integer> futureTask2 = new FutureTask<Integer>(new Callable() {
            @Override
            public Integer call() throws Exception {
                System.out.println("开始执行futureTask2");
                for (long i = 0; i <10000000000L ; i++) {
                }
                return 2;
            }
        });
        new Thread(futureTask1).start();
        new Thread(futureTask2).start();
        System.out.println("futureTask1返回值："+futureTask1.get());
        System.out.println("futureTask2返回值："+futureTask2.get());
        System.out.println("Callable执行用时："+(System.currentTimeMillis()-currentTime2)/1000.00+"s");
    }
}
